use crate::knowledge_graph::{KnowledgeGraph, Relation};
use crate::reasoning_chain::{ReasoningChain, ReasoningResult};
use crate::nlp::Tokenizer;
use rand::Rng;

/// 主动学习对话系统
pub struct ActiveLearningDialogue {
    reasoning_chain: ReasoningChain,
    tokenizer: Tokenizer,
    conversation_history: Vec<(String, String)>,
    curiosity_level: f64, // 0.0-1.0，好奇心水平
    learning_mode: bool,   // 是否处于学习模式
}

impl ActiveLearningDialogue {
    pub fn new() -> Self {
        let mut tokenizer = Tokenizer::new();
        
        // 基础词表
        let vocab = vec![
            "你", "我", "是", "的", "吗", "什么", "为什么", "如何", "能", "会",
            "好", "谢谢", "再见", "对不起", "请", "帮", "教", "学", "知道", "理解",
        ];
        tokenizer.add_words(&vocab);

        let kg = KnowledgeGraph::new();
        let reasoning_chain = ReasoningChain::new(kg);

        ActiveLearningDialogue {
            reasoning_chain,
            tokenizer,
            conversation_history: Vec::new(),
            curiosity_level: 0.8,
            learning_mode: true,
        }
    }

    /// 处理对话
    pub fn chat(&mut self, user_input: &str) -> String {
        println!("\n{}", "=".repeat(60));
        println!("【主动学习对话系统】");
        println!("{}", "=".repeat(60));
        println!("👤 用户: {}", user_input);

        // 1. 检查是否是教学模式
        if self.is_teaching_statement(user_input) {
            return self.learn_from_teaching(user_input);
        }

        // 2. 使用推理链处理问题
        let result = self.reasoning_chain.reason(user_input);

        // 3. 生成回复
        let response = self.generate_response(user_input, &result);

        // 4. 从对话中学习
        self.reasoning_chain.learn_from_dialogue(user_input, &response);

        // 5. 记录对话
        self.conversation_history.push((user_input.to_string(), response.clone()));

        // 6. 显示推理过程
        if !result.reasoning_steps.is_empty() {
            println!("\n{}", self.reasoning_chain.explain());
        }

        println!("\n🤖 AI: {}\n", response);
        response
    }

    /// 判断是否是教学语句
    fn is_teaching_statement(&self, input: &str) -> bool {
        // 排除所有问句
        let is_question = input.ends_with('吗') 
            || input.ends_with('？') 
            || input.ends_with('呢')
            || input.starts_with("什么")
            || input.starts_with("为什么")
            || input.starts_with("如何")
            || input.starts_with("怎么");
        
        if is_question {
            return false;
        }
        
        // 检查是否是教学模式
        input.contains("是") 
            || input.contains("就是")
            || input.contains("意思是")
            || input.contains("指的是")
    }

    /// 从教学中学习
    fn learn_from_teaching(&mut self, input: &str) -> String {
        println!("\n📖 检测到教学语句，进入学习模式...");

        // 清理输入，去除引号
        let cleaned_input = input
            .replace('"', "")
            .replace('"', "")
            .replace('"', "")
            .replace("'", "")
            .replace("'", "")
            .replace("'", "");

        // 解析多种教学模式
        // 模式1: "A是B"
        // 模式2: "A是一种B"
        // 模式3: "A意思是B"
        // 模式4: "A指的是B"
        
        let patterns = [
            ("是一种", 9),
            ("意思是", 9), 
            ("指的是", 9),
            ("就是", 6),
            ("是", 3),
        ];
        
        for (pattern, offset) in patterns {
            if let Some(pos) = cleaned_input.find(pattern) {
                let concept = cleaned_input[..pos].trim();
                let definition = cleaned_input[pos + offset..].trim()
                    .trim_end_matches(&['。', '，', '！', '？', '吗', '呢'][..]);

                // 额外检查：过滤掉明显的噪音
                if !concept.is_empty() && !definition.is_empty() 
                    && concept.len() >= 2 && definition.len() >= 2 {
                    
                    println!("  ✅ 成功解析:");
                    println!("     概念: {}", concept);
                    println!("     定义: {}", definition);
                    
                    self.reasoning_chain.knowledge_graph_mut()
                        .add_concept(concept, definition, "用户教学");

                    // 尝试提取关系
                    self.extract_relations(concept, definition);

                    let responses = vec![
                        format!("原来{}是{}！我记住了。", concept, definition),
                        format!("明白了，{}指的是{}。谢谢你教我！", concept, definition),
                        format!("学到了！所以{}就是{}对吗？", concept, definition),
                        format!("很有趣！{}是{}，我会记在心里。", concept, definition),
                        format!("好的！我现在知道{}了。", concept),
                    ];

                    let mut rng = rand::thread_rng();
                    return responses[rng.gen_range(0..responses.len())].clone();
                }
            }
        }

        "我在努力理解你说的内容，能换个方式再说一遍吗？".to_string()
    }

    /// 提取概念间的关系
    fn extract_relations(&mut self, concept: &str, definition: &str) {
        let kg = self.reasoning_chain.knowledge_graph_mut();

        // 识别"是...的一种"模式
        if definition.contains("的一种") || definition.contains("一种") {
            let parts: Vec<&str> = definition.split("的一种").collect();
            if parts.len() == 2 {
                let parent = parts[0].trim();
                kg.add_relation(Relation::IsA(concept.to_string(), parent.to_string()));
                println!("  • 学到关系: {} 是 {} 的一种", concept, parent);
            }
        }

        // 识别"属于"模式
        if definition.contains("属于") {
            let parts: Vec<&str> = definition.split("属于").collect();
            if parts.len() >= 2 {
                let parent = parts[1].trim();
                kg.add_relation(Relation::IsA(concept.to_string(), parent.to_string()));
            }
        }

        // 识别"能够"模式
        if definition.contains("能够") || definition.contains("可以") {
            kg.add_relation(Relation::CanDo(
                concept.to_string(),
                definition.to_string(),
            ));
        }
    }

    /// 生成回复
    fn generate_response(&mut self, _input: &str, result: &ReasoningResult) -> String {
        // 如果需要学习，返回好奇的问题
        if result.requires_learning && !result.learning_questions.is_empty() {
            let question = &result.learning_questions[0];
            return format!("{}这样我就能更好地理解和回答你的问题了。", question);
        }

        // 如果有答案，返回答案
        if let Some(answer) = &result.answer {
            if result.confidence > 0.5 {
                return answer.clone();
            } else {
                return format!("{}不过我不是很确定，你能告诉我更多吗？", answer);
            }
        }

        // 默认回复
        let default_responses = vec![
            "这个问题很有趣！你能教教我吗？",
            "我还在学习中，能否解释一下？",
            "让我想想...你指的是什么意思？",
        ];

        let mut rng = rand::thread_rng();
        default_responses[rng.gen_range(0..default_responses.len())].to_string()
    }

    /// 执行自我推理（主动思考）
    pub fn self_reflect(&mut self) {
        println!("\n🤔 进行自我反思...");

        // 推理新知识
        let inferences = self.reasoning_chain.knowledge_graph_mut().infer_new_knowledge();
        
        if !inferences.is_empty() {
            println!("💡 通过推理得出新知识:");
            for inference in &inferences {
                println!("  • {}", inference);
            }
        }

        // 显示知识图谱统计
        println!("\n{}", self.reasoning_chain.knowledge_graph().get_stats());
    }

    /// 导出学到的知识
    pub fn export_knowledge(&self) -> Vec<String> {
        self.reasoning_chain.knowledge_graph().export_knowledge()
    }

    /// 获取对话历史
    pub fn get_history(&self) -> &[(String, String)] {
        &self.conversation_history
    }

    /// 清除历史
    pub fn clear_history(&mut self) {
        self.conversation_history.clear();
    }

    /// 获取推理链的可变引用
    pub fn reasoning_chain_mut(&mut self) -> &mut ReasoningChain {
        &mut self.reasoning_chain
    }

    /// 保存知识图谱
    pub fn save_knowledge(&self, path: &str) -> std::io::Result<()> {
        use std::fs::File;
        use std::io::Write;

        let knowledge = self.export_knowledge();
        let mut file = File::create(path)?;
        
        for line in knowledge {
            writeln!(file, "{}", line)?;
        }

        Ok(())
    }
}

impl Default for ActiveLearningDialogue {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_active_learning() {
        let mut ald = ActiveLearningDialogue::new();
        
        // 教学
        let response = ald.chat("深度学习是机器学习的一种");
        assert!(response.contains("记住") || response.contains("学到"));

        // 查询
        let response2 = ald.chat("什么是深度学习");
        assert!(!response2.is_empty());
    }

    #[test]
    fn test_reasoning() {
        let mut ald = ActiveLearningDialogue::new();
        ald.chat("AI是人工智能");
        ald.self_reflect();
        
        let knowledge = ald.export_knowledge();
        assert!(!knowledge.is_empty());
    }
}

